package socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;

public class ChatServer {
        public static Set<ChatChannel> channels = new HashSet<ChatChannel>();
        
        public ChatServer() {
                channels.add(new ChatChannel("default"));
                channels.add(new ChatChannel("first"));
                channels.add(new ChatChannel("second"));
        } 
        
        public static void main(String[] args) {
                ChatServer chatServer = new ChatServer();
                chatServer.startServer();
        }
        
        //[DF] XXX: There is no ClassNotFoundException and InterruptedException thrown here. Dead code?
        public void startServer() {
                ServerSocket providerSocket = null;
                Socket connection = null;
                
                final int port = 2005;
                
                boolean listening = true;
                
                try {
                        providerSocket = new ServerSocket(port);
                        System.out.println("Waiting for connection");
                } catch (IOException e){
                        System.out.println("Could not listen on port: " + port);
                        return;
                }
                
                ChatChannel defaultChannel = ChatChannel.getByName("default");
                
                while (listening){
                        try {
                                connection = providerSocket.accept();
                                new ChatServerClientThread(connection, defaultChannel).start();
                        } catch (IOException e) {
                                System.out.println("Server failed");
                        }
                }
                
                for (ChatChannel channel: channels)
                        channel.close();
                
                try {
                        providerSocket.close();
                } catch (IOException e) {
                        System.out.println("Server failed");
                }
        }
}